package info.empathymobile.forecast.testenv;

import info.empathymobile.forecast.testenv.beans.TestBaseData;
import info.empathymobile.forecast.testenv.beans.TestLog;
import info.empathymobile.forecast.testenv.business.LocalDBConnection;
import info.empathymobile.forecast.testenv.business.ServerConnection;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ServerController {
	private Context myContext;
	private String authKey;
	private LocalDBConnection localDBConnection;
	private ServerConnection serverConnection;
	
	public ServerController(Context context){
		this.myContext = context;
		this.authKey = context.getString(R.string.empathy_sync_auth_key);
		this.localDBConnection = new LocalDBConnection(context);
		this.serverConnection = new ServerConnection(authKey);
	}
	
	private void printLogLine(String logMsg){
		((TestLogOutput) myContext).printLogMsg(logMsg);
	}
	
	public boolean hasWiFiConnectivity() {
		ConnectivityManager cm = (ConnectivityManager) this.myContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		
		if(activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnected() 
				&& activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
			return true;
		}
		else {
			return false;
		}
	}
	
	public List<TestBaseData> getTestBaseData(List<TestBaseData> params) {
		if(hasWiFiConnectivity()){
			List<TestBaseData> testBaseDataFromServer = new ArrayList<TestBaseData>();
			if(!params.isEmpty()){
				printLogLine("Collecting New Test Data From Server...");
				testBaseDataFromServer.addAll(serverConnection.getNewTestBaseDataFromServer(params));
				
				printLogLine("Saving New Test Data On Local DB...");
				localDBConnection.saveTestBaseDataCollection(testBaseDataFromServer);
			}
			else {
				printLogLine("Params Empty! Nothing From Server!");
			}
			return testBaseDataFromServer;
		}
		else {
			printLogLine("# No WiFi Connectivity #");
		}
		return null;
	}

	public int sendTestLogsToServer() {
		List<TestLog> allTestLogOnDB = localDBConnection.getAllTestLogs();
		if(hasWiFiConnectivity()){
			List<Integer> syncronizedIds = new ArrayList<Integer>();
			
			if(!allTestLogOnDB.isEmpty()){
				syncronizedIds = serverConnection.sendTestLogsToServer(allTestLogOnDB);
				localDBConnection.deleteTestLogById(syncronizedIds);
			}
			if(syncronizedIds != null){
				return allTestLogOnDB.size() - syncronizedIds.size();
			}
			else {
				printLogLine("Problem with server");
			}
		}
		else {
			printLogLine("# No WiFi Connectivity #");
		}
		return allTestLogOnDB.size();
	}
}
